package edu.manju.mimi.lord.service;

import cn.hutool.core.util.NumberUtil;
import com.github.cm.heclouds.onenet.studio.api.IotClient;
import com.github.cm.heclouds.onenet.studio.api.IotProfile;
import com.github.cm.heclouds.onenet.studio.api.entity.common.CreateDeviceRequest;
import com.github.cm.heclouds.onenet.studio.api.entity.common.CreateDeviceResponse;
import com.github.cm.heclouds.onenet.studio.api.entity.common.DeleteDeviceRequest;
import com.github.cm.heclouds.onenet.studio.api.entity.common.DeleteDeviceResponse;
import com.github.cm.heclouds.onenet.studio.api.exception.IotClientException;
import com.github.cm.heclouds.onenet.studio.api.exception.IotServerException;
import edu.manju.mimi.lord.config.OnenetConfig;
import org.springframework.stereotype.Service;

/**
 * <h4>mimi-lord-server</h4>
 * <p>提供设备服务</p>
 *
 * @author : Lebei(lebei163@163.com)
 * @date : 2023-03-03 16:52
 **/
@Service
public class IotDeviceService {
    private final IotClient iotClient;

    private final String productId;

    public IotDeviceService(OnenetConfig config) {
        IotProfile profile = new IotProfile();
        profile.userId(config.getUserId())
                .accessKey(config.getAccessKey());

        this.productId = config.getProductId();
        this.iotClient = IotClient.create(profile);
    }

    public CreateDeviceResponse createDevice(Integer userId, Integer deviceId, String deviceDesc)
            throws IotServerException, IotClientException {

        CreateDeviceRequest request = new CreateDeviceRequest();
        request.setProductId(this.productId);
        request.setDeviceName(getDeviceName(userId, deviceId));
        request.setDesc(deviceDesc);

        return iotClient.sendRequest(request);
    }

    public DeleteDeviceResponse deleteDevice(Integer userId, Integer deviceId)
            throws IotServerException, IotClientException {

        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setProductId(this.productId);
        request.setDeviceName(getDeviceName(userId, deviceId));

        return iotClient.sendRequest(request);
    }

    private String getDeviceName(Integer userId, Integer deviceId) {
        return String.format("%s-%s",
                NumberUtil.decimalFormat("00000000", userId),
                NumberUtil.decimalFormat("00000000", deviceId));
    }
}
